//
//  FlipsideViewController.m
//  Mayhem
//
//  Created by Jay Meistrich on 6/20/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FlipsideViewController.h"
#import "QRCodeReader.h"

@implementation FlipsideViewController

@synthesize delegate=_delegate;
@synthesize segmentedControl;
@synthesize labelIP;
@synthesize labelPort;
@synthesize textFieldIP;
@synthesize textFieldPort;
@synthesize buttonScan;
@synthesize labelDescription;

-(IBAction) segmentedControlIndexChanged{
    switch (self.segmentedControl.selectedSegmentIndex) {
        case 0:
            self.buttonScan.alpha = 1;
            self.labelDescription.alpha = 1;
            self.labelIP.alpha = 0;
            self.labelPort.alpha = 0;
            self.textFieldIP.alpha = 0;
            self.textFieldPort.alpha = 0;
            break;
        case 1:
            self.buttonScan.alpha = 0;
            self.labelDescription.alpha = 0;
            self.labelIP.alpha = 1;
            self.labelPort.alpha = 1;
            self.textFieldIP.alpha = 1;
            self.textFieldPort.alpha = 1;
            break;
        default:
            break;
    }
}

- (void)closeSettings
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ServiceIPSet" object:nil];
    [self.delegate flipsideViewControllerDidFinish:self];
}

- (void)setTextFields
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *ip = [prefs stringForKey:@"IP"];
    if(ip != nil)
    {
        NSString *port = [prefs stringForKey:@"Port"];
        [textFieldIP setText:ip];
        [textFieldPort setText:port];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textBoxName {
	[textBoxName resignFirstResponder];
	return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
    UITouch *touch = [[event allTouches] anyObject];
    if ([textFieldIP isFirstResponder] && (textFieldIP != touch.view))
    {
        [textFieldIP resignFirstResponder];
        // textField1 lost focus
    }
    
    if ([textFieldPort isFirstResponder] && (textFieldPort != touch.view))
    {
        [textFieldIP resignFirstResponder];
        // textField2 lost focus
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    if(textField == textFieldIP)
    {
        [prefs setObject:textField.text forKey:@"IP"];
    }
    else if(textField == textFieldPort)
    {
        [prefs setObject:textField.text forKey:@"Port"];
    }
    [prefs synchronize];
}

- (IBAction)scanPressed:(id)sender 
{
    ZXingWidgetController *widController = [[ZXingWidgetController alloc] initWithDelegate:self showCancel:YES OneDMode:NO];
    QRCodeReader* qrcodeReader = [[QRCodeReader alloc] init];
    NSSet *readers = [[NSSet alloc ] initWithObjects:qrcodeReader,nil];
    [qrcodeReader release];
    widController.readers = readers;
    [readers release];
    //    NSBundle *mainBundle = [NSBundle mainBundle];
    widController.soundToPlay = nil;
    //    [NSURL fileURLWithPath:[mainBundle pathForResource:@"beep-beep" ofType:@"aiff"] isDirectory:NO];
    [self presentModalViewController:widController animated:YES];
    [widController release];
}


#pragma mark -
#pragma mark ZXingDelegateMethods

- (void)zxingController:(ZXingWidgetController*)controller didScanResult:(NSString *)result {
//    self.resultsToDisplay = result;
    if (self.isViewLoaded) {
    //    [resultsView setText:result];
    //    [resultsView setNeedsDisplay];
    }
    [self dismissModalViewControllerAnimated:NO];
    
    NSArray *splitSourceData = [result componentsSeparatedByString:@":"];
    
    // This is usually an object that has a series of Array's and Dictionaries to store and organize the incoming data
    NSString *port = [splitSourceData objectAtIndex:0];
    NSString *ip;
    if([splitSourceData count] > 2)
    {
        NSMutableString *ipText = [NSMutableString stringWithString:[splitSourceData objectAtIndex:1]];
        for(int i = 2; i < [splitSourceData count]; i ++)
        {
            [ipText appendString: @";"];
            [ipText appendString: [splitSourceData objectAtIndex:i]];
        }
        ip = ipText;
    }
    else
    {
        ip = [splitSourceData objectAtIndex:1];   
    }
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:ip forKey:@"IP"];
    [prefs setObject:port forKey:@"Port"];
    [prefs synchronize];
    
    [self setTextFields];
    
    [self closeSettings];
}

- (void)zxingControllerDidCancel:(ZXingWidgetController*)controller {
    [self dismissModalViewControllerAnimated:YES];
}


- (void)dealloc
{
    [segmentedControl release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) 
    {
        hasCamera = YES;
        self.labelIP.alpha = 0;
        self.labelPort.alpha = 0;
        self.textFieldIP.alpha = 0;
        self.textFieldPort.alpha = 0;
    }
    else 
    {
        hasCamera = NO;
        self.segmentedControl.selectedSegmentIndex = 1;
        self.segmentedControl.hidden = YES;
    }
    [self setTextFields];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Actions

- (IBAction)done:(id)sender
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:textFieldIP.text forKey:@"IP"];
    [prefs setObject:textFieldPort.text forKey:@"Port"];
    [prefs synchronize];
    [self closeSettings];
}

@end
